<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/base.css">
    <title>Increment Counter</title>
</head>
<body>
    <div class="counter-container">
        <img src="./image/1.png" alt="1">
        <div class="counter" data-target="12220">0</div>
        <span>粉丝数</span>
    </div>
    <div class="counter-container">
        <img src="./image/2.png" alt="1">
        <div class="counter" data-target="14310">0</div>
        <span>订阅数</span>
    </div>
    <div class="counter-container">
        <img src="./image/3.png" alt="1">
        <div class="counter" data-target="1440">0</div>
        <span>发布数</span>
    </div>
    <script>
        const counter = document.querySelectorAll('.counter')
        //定时器方法
        // counter.forEach(counter => {
        //     const target = counter.getAttribute('data-target')
        //     // for(let i =0 ; i<=target; i++){
        //     //     counter.textContent = i;
        //     // }
        //     let i = 0;
        //     const increment = parseInt(target/50);
        //     const timer = setInterval(()=>{
        //         // i++
        //         i += increment
        //         if(i >= Number(target)){
        //             clearInterval(timer)
        //         }
        //         counter.textContent = target;
        //     },17)
        // })
        //使用window.requestAnimationFrame
            counter.forEach(counter=>{
                const target = counter.getAttribute('data-target')
                const increment = parseInt(target/50) //每次加的份数 暂时理解为
                let i = 0
                const counterPlus = () => {
                    i += increment
                    counter.textContent = i
                    if(i<target){
                        requestAnimationFrame(counterPlus)
                    }else{
                        counter.textContent = target
                    }
                }
                requestAnimationFrame(counterPlus)
            })
    </script>
</body>
</html>